package com.yuanli.cosmeticmirror.model.impl;

import androidx.lifecycle.LifecycleOwner;

import com.alibaba.fastjson.JSON;
import com.comenjoysoft.baselibrary.listener.CallbackListener;
import com.comenjoysoft.baselibrary.util.SPUtils;
import com.orhanobut.logger.Logger;
import com.rxjava.rxlife.BaseScope;
import com.rxjava.rxlife.RxLife;
import com.yuanli.cosmeticmirror.base.Constant;
import com.yuanli.cosmeticmirror.base.HttpApi;
import com.yuanli.cosmeticmirror.bean.FavoriteBean;
import com.yuanli.cosmeticmirror.bean.videoBean;
import com.yuanli.cosmeticmirror.model.biz.IFaoriteBiz;

import rxhttp.wrapper.param.RxHttp;

public class FavoriteImpl extends BaseScope implements IFaoriteBiz {
    public FavoriteImpl(LifecycleOwner owner) {
        super(owner);
    }

    @Override
    public void getFavorite(CallbackListener<FavoriteBean> listener) {
        RxHttp.get(HttpApi.GET_COLLECT_LIST)
                .add("userid", SPUtils.getInstance().getString(Constant.SP_USER_ACCOUNT))
                .asString()
                .as(RxLife.asOnMain(this)) //返回String类型
                .subscribe(s -> {          //订阅观察者，
                    Logger.d(" getFavorite onSuccess: " + s);
                    FavoriteBean response = JSON.parseObject(s, FavoriteBean.class);
                    if (response.getData() != null) {
                        listener.success(response);
                    } else {
                        listener.failed(null);
                    }
                }, throwable -> {
                    Logger.d(" getFavorite onFailed: " + throwable.getMessage());
                    //请求失败
                    listener.failed(throwable.getMessage());
                });
    }

    @Override
    public void cancelCollect(String tutorialId, CallbackListener<videoBean> listener) {
        RxHttp.postJson(HttpApi.POST_DELETE_COLLECT)
                .add("userid", SPUtils.getInstance().getString(Constant.SP_USER_ACCOUNT))
                .add("id", tutorialId)
                .asString()
                .as(RxLife.asOnMain(this)) //返回String类型
                .subscribe(s -> {          //订阅观察者，
                    Logger.d(" cancelCollect onSuccess: " + s);
                    videoBean response = JSON.parseObject(s, videoBean.class);
                    if (response.getCode() == 1) {
                        listener.success(response);
                    } else {
                        listener.failed(null);
                    }
                }, throwable -> {
                    Logger.d(" cancelCollect onFailed: " + throwable.getMessage());
                    //请求失败
                    listener.failed(throwable.getMessage());
                });
    }
}
